package com.pgy.general.util;


import com.pgy.general.entity.User;
import com.pgy.general.exceptions.LoginRuntimeException;
import com.pgy.general.exceptions.generalRuntimeException;
import com.pgy.general.service.IUserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

/**
 * @Auther:superChao
 * @Date: 2021/01/26/16:52
 * @Version:2.0.0
 * 生成token工具类，Main中含对工具类使用演示（生成token、解析token）
 */
public class TokenUtil {
    @Autowired
    private IUserService iUserService;

    public static void main(String[] args) {
        /*User user=new User();
        user.setUsername("yyc");
        user.setId(123522);
       String tokgien=getToken(user);*/
        // System.out.println(token);
        String token="";
        Claims claims1 = Jwts.parser()
                .setSigningKey("assh -T git@gitee.com1g2y47dg3dj59fjhhsd7cnewy73j")
                .parseClaimsJws(token)
                .getBody();
        Date d1 = claims1.getIssuedAt();
        Date d2 = claims1.getExpiration();
        System.out.println("登录用户的id：" + claims1.getId());
        System.out.println("登录用户的名称：" + claims1.getSubject());
        System.out.println("令牌签发时间：" + sdf.format(d1));
        System.out.println("令牌过期时间：" + sdf.format(d2));
    }

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    //生成token
    public static String getToken(User user, HttpServletRequest httpServletRequest) {
        if(user.getId()!=null) {
            String remortIp=IPUtil.getRemortIP(httpServletRequest);
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",user.getId().toString());
            claims.put("username",user.getUsername());
            claims.put("remortIp",remortIp);
            long current=System.currentTimeMillis();//当前时间毫秒数
            long zero=current/(1000*3600*24)*(1000*3600*24)- TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
            long twelve=zero+24*60*60*1000*10;
            String token = "";
            token= Jwts.builder()
                    .setClaims(claims)
                    .setId(user.getId().toString())//登录用户id
                    .setSubject(user.getUsername())
                    .setExpiration(new Date(twelve))
                    .setIssuedAt(new Date(System.currentTimeMillis()))
                    .signWith(SignatureAlgorithm.HS512,"a1g2y47dg3dj59fjhhsd7cnewy73j")//头部信息 第一个参数为加密方式为哈希512  第二个参数为加的盐为secret字符串
                    .compact();
            return token;
        }
        return null;
    }

    //解析验证token
    public static String verifyToken(String token) {
        String result = "";
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey("a1g2y47dg3dj59fjhhsd7cnewy73j")
                    .parseClaimsJws(token)
                    .getBody();
            result ="TOKEN_VALID";
        } catch (Exception e) {
            result ="TOKEN_INVALID";
        }
        return result;
    }
    public static String getUserByToken(HttpServletRequest request){
        String token = request.getHeader("token");
        String userId=null;
        try {
            Claims claims1 = Jwts.parser()
                    .setSigningKey("a1g2y47dg3dj59fjhhsd7cnewy73j")
                    .parseClaimsJws(token)
                    .getBody();
        userId=claims1.getId();
        }catch (Exception e){
            throw new LoginRuntimeException("获取用户信息异常，请重新登录！");
        }
        return userId;
    }



}
